﻿#include "library.h"
#include <QDebug>

Library::Library(QObject *parent) : QObject(parent)
{
    mq = DownloadMQ::Instance();  //初始化单例
    init();
}

bool Library::isExist(QString &version)
{
    auto val = library_vector.find(version);
    if(val != library_vector.end())
    {
        return true;
    }
    return false;
}

bool Library::update(QJsonObject object)
{
    qDebug()<<"获取 各个模块";
    //沉下心，慢慢搞，不要急，最好的话就找个伙伴
    //首先是assetIndex,,,这个先不弄，比其他的稍微复杂了一点
    QJsonObject assetIndex = object["assetIndex"].toObject();
    
    //紧接着是downloads的东西
    QJsonObject downloads  = object["downloads"].toObject();
    QJsonObject client = downloads["client"].toObject();
    QJsonObject client_mappings = downloads["client_mappings"].toObject();
    QJsonObject server = downloads["server"].toObject();
    QJsonObject server_mappings = downloads["server_mappings"].toObject();
    
    //然后是libraries，这是一个array，或许用个for去循环下载会更更加合适
    QJsonArray libraries = object["libraries"].toArray();
    
    qDebug()<<"进入下载";
    updateUnitFile(assetIndex);
    
    QString assetIndexurl = assetIndex["url"].toString();
    CFile file;
    if(mq->getFile(assetIndexurl,&file))
    {
        qDebug()<<"下载资源文件";
        QByteArray assetBuffer(file.data,file.size);
        QJsonObject assetArry = QJsonDocument::fromJson(assetBuffer).object()[];
        
    }
    
    updateUnitFile(client);
    updateUnitFile(client_mappings);
    updateUnitFile(server);
    updateUnitFile(server_mappings);
    for(int i=0;i<libraries.size();i++)
    {
        //qDebug()<<"artifact: "<<libraries[i];
        QJsonObject artifact = libraries[i]
                .toObject()["downloads"]
                .toObject()["artifact"].toObject();
        updateUnitFile(artifact);
        
    }
    return true;
}

void Library::updateUnitFile(QJsonObject unit)
{
    QString url = unit["url"].toString();
    qDebug()<<"updateUnitFile "<<unit;
    if(url.isEmpty())
    {
        return;
    }
    
    if(mq->getFileDatabase(url))
    {
        qDebug()<<"文件存在 ";
        return;
    }
    
    mq->download(unit);
}

void Library::init()
{
    qDebug()<<"仓库初始化";
    QDir cfgPathDir = Config::getLibrary_path();
    if(!cfgPathDir.exists()){
        return;
    }
    cfgPathDir.setFilter(QDir::AllDirs); //设置类型过滤器，只为文件格式
    int dirCount = cfgPathDir.count();
    if(dirCount <= 0){
        return;
    }
    for(int i=0; i<dirCount; i++) {
        QString fileName = cfgPathDir[i];
        QDir dir(fileName);
        qDebug()<<"版本: "<<fileName;
        library_vector.insert(fileName,dir);
    }
}
